﻿using System;
using System.Collections.Generic;
using System.IO;
using IteraProvisioning.Core;
using Microsoft.SharePoint.Client;

namespace ProvisioningLibrary.Handlers
{
    public class AppCatalogHandler : Handler
    {
        private List<AppInstance> _appsList;

        public AppCatalogHandler()
        {
            _appsList = new List<AppInstance>();
        }

        public List<AppInstance> AppsList
        {
            get { return _appsList; }
        }

        public void ManageAppWeb(string urlSubsite)
        {
            using (var context = GetContext(urlSubsite))
            {
                ConfigureWeb(context);
            }
        }

        private void ConfigureWeb(ClientContext context)
        {
            Guid sideloadingFeature = new Guid("AE3A1339-61F5-4f8f-81A7-ABD2DA956A7D"); // Sideloading feature Id. Activate it only for dev purposes!
            // Activate required features for app catalog
            context.Site.ActivateFeature(sideloadingFeature);
            DeployToAppCatalog(context, Properties.Resources.CustomerDetailsAppPart, "CustomerDetailsAppPart");
            context.Site.DeactivateFeature(sideloadingFeature);
        }

        private void DeployToAppCatalog(ClientContext context, byte[] appBytes, string appTitle)
        {
            List appList = context.Web.GetListByTitle("Apps for SharePoint");
            if (appList != null)
            {
                // Upload app file to list of apps for sharepoint
                appList.RootFolder.UploadFile(appTitle, new MemoryStream(appBytes), null, true, false);
                // Install the app in app catalog
                _appsList.Add(context.Web.DeployApp(new MemoryStream(appBytes), appTitle));
            }
        }
    }
}